#include "CLink/Router/StandardRouteHandler.h"
#include "CLink/Utils/StringUtils.h"
#include "CLink/error/ErrorHandler.h"

#include <Poco/URI.h>
#include <Poco/Net/HTMLForm.h>

namespace CLink
{
namespace Router
{

StandardRouteHandler::StandardRouteHandler(const std::string &path,
                                            const std::string &method,
                                            HandlerFunction handler,
                                            int priority)
    : BaseRouteHandler(path, method, priority), m_handler(handler)
{
}

bool StandardRouteHandler::handle(RequestContext &context)
{
    try
    {
        // 提取路由参数
        if (getMethod() != Poco::Net::HTTPRequest::HTTP_POST && getMethod() != Poco::Net::HTTPRequest::HTTP_PUT)
        {
            // 验证查询参数
            if (!validateQueryParams(context))
            {
                throw CLink::Error::CLinkException(CLink::Error::ErrorCode::INVALID_ARGUMENT, "Invalid query parameters");
            }

            auto dynamicParams = extractDynamicParams(context);
            auto queryParams = extractQueryParams(context);
            // 合并参数到context.params
            context.dynamicParams.swap(dynamicParams);
            context.queryParams.swap(queryParams);
        }

        // 调用处理函数
        if (m_handler)
        {
            m_handler(context);
            return true;
        }

        return false;
    }
    catch (const CLink::Error::CLinkException &e)
    {
        // 重新抛出错误，让错误处理器处理
        throw;
    }
    catch (const std::exception &e)
    {
        // 将其他异常转换为CLinkException对象
        throw CLink::Error::CLinkException(CLink::Error::ErrorCode::INTERNAL_ERROR, e.what());
    }
}

StandardRouteHandler &StandardRouteHandler::setHandler(HandlerFunction handler)
{
    m_handler = handler;
    return *this;
}

} // namespace Router
} // namespace CLink